// app/model/collection_record_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE, TEXT, ENUM } = app.Sequelize;

  const CollectionRecord = app.model.define('collectionRecord', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    organizationId: {
      type: INTEGER,
      allowNull: false,
      field: 'organization_id',
      comment: '组织ID'
    },
    salesOrderId: {
      type: INTEGER,
      allowNull: false,
      field: 'sales_order_id',
      comment: '销售订单ID'
    },
    collectionDate: {
      type: DATE,
      allowNull: false,
      field: 'collection_date',
      comment: '催款日期'
    },
    collectionMethod: {
      type: ENUM('phone', 'email', 'visit'),
      defaultValue: 'phone',
      field: 'collection_method',
      comment: '催款方式'
    },
    contactPerson: {
      type: STRING(100),
      field: 'contact_person',
      comment: '联系人'
    },
    responseResult: {
      type: TEXT,
      field: 'response_result',
      comment: '催款结果'
    },
    nextFollowupDate: {
      type: DATE,
      field: 'next_followup_date',
      comment: '下次跟进日期'
    },
    createdBy: {
      type: INTEGER,
      allowNull: false,
      field: 'created_by',
      comment: '操作人'
    },
    createdAt: {
      type: DATE,
      field: 'created_at'
    },
    updatedAt: {
      type: DATE,
      field: 'updated_at'
    }
  }, {
    tableName: 'collection_records',
    timestamps: true
  });

  // 添加关联关系
  CollectionRecord.associate = function() {
    // 催款记录与销售订单的关联
    if (app.model.SalesOrderModel) {
      CollectionRecord.belongsTo(app.model.SalesOrderModel, {
        foreignKey: 'salesOrderId',
        as: 'order'
      });
    }

    // 催款记录与组织的关联
    if (app.model.OrganizationModel) {
      CollectionRecord.belongsTo(app.model.OrganizationModel, {
        foreignKey: 'organizationId',
        as: 'organization'
      });
    }
  };

  return CollectionRecord;
};